package com.zcx.qshop.flow;

import java.util.List;

import android.content.Context; 
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup; 
import android.widget.BaseAdapter;
import android.widget.RelativeLayout;

import com.zcx.qshop.QSApplication;

public abstract class ViewFlowAdvert<T> extends RelativeLayout{
	
	private ViewFlow viewFlow;
	
	private CircleFlowIndicator circleFlowIndicator;
	
	private Adapter adapter;
	
	private LayoutInflater layoutInflater; 

	public ViewFlowAdvert(Context context, AttributeSet attrs) {
		
		super(context, attrs);
		
		layoutInflater = LayoutInflater.from(context);
		
		addView(viewFlow = new ViewFlow(getContext()));
		
		viewFlow.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		
		addView(indicatorLayout(circleFlowIndicator = new CircleFlowIndicator(getContext())));
		
		LayoutParams linearLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		
		linearLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, -1);

		linearLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
		
		circleFlowIndicator.setLayoutParams(linearLayoutParams);

		int temp = QSApplication.ScaleScreenHelper.getWidthHeight(15);

		circleFlowIndicator.setPadding(temp, temp, temp, temp);

		circleFlowIndicator.setVisibility(View.GONE);
        
        viewFlow.setFlowIndicator(circleFlowIndicator);
        
        viewFlow.setTimeSpan(3000);
        
        viewFlow.setSelection(3 * 1000);
        
        viewFlow.startAutoFlowTimer();
		
 	}
	
	public void setItems(List<T> list){

		circleFlowIndicator.setVisibility(View.VISIBLE);

        viewFlow.setmSideBuffer(list.size());
		
		viewFlow.setAdapter(adapter = new Adapter(list)); 
		
	} 
	
	protected View indicatorLayout(CircleFlowIndicator circleFlowIndicator){
		
		return circleFlowIndicator;
		
	}
	
	protected LayoutInflater getLayoutInflater(){
		
		return layoutInflater;
		
	}

	public void setOnTouchListener(OnTouchListener onTouchListener){

		viewFlow.setOnTouchListener(onTouchListener);

	}
	
	private class Adapter extends BaseAdapter{
		
		private List<T> list;
		
		public Adapter(List<T> list){
			
			this.list = list;
			
		}

		@Override
		public int getCount() {
			
 			return list.size() > 1 ? Integer.MAX_VALUE : list.size(); 
 			
		}

		@Override
		public Object getItem(int arg0) { 
			
 			return arg0;
 			
		}

		@Override
		public long getItemId(int arg0) {
			
 			return arg0;
 			
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			
			if(arg1 == null){
				
				arg1 = createView();
				
			}
			
 			return loadView(arg1, list.get(list.size() > 1 ? arg0 % list.size() : arg0));
 			
		}
		
	} 
	
	protected abstract View loadView(View view, T t);

	protected abstract View createView();

}
